<?php

namespace addons\classroom\controller\api;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Config;
use think\Db;
use think\Lang;
use think\Validate;
use addons\classroom\library\Qwechat;
use Exception;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'register', 'qy_wechat_login','mp_mini_login'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(ROOT_PATH . '/addons/classroom/lang/zh-cn/user.php');

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 检测是否首次设置密码
     * data = 0 ; 第一次设置密码
     */
    public function wpd_status()
    {
        $pwd = Db::name('user')->where('id',$this->auth->id)->value('password');
        if($pwd === '' || is_null($pwd)){
            $data = ['code'=>1,'data'=>0];
        } else {
            $data = ['code'=>1,'data'=>1];
        }
        return json($data);
    }

    /**
     * 修改密码
     */
    public function wpd_edit()
    {
        $pwd = Db::name('user')->where('id',$this->auth->id)->value('password');
        $pwd = $pwd === '' || is_null($pwd) ? false : true;

        $new_password = $this->request->param('new_password');
        $new_password2 = $this->request->param('new_password2');
        $old_password = $this->request->param('old_password');

        if($pwd){
            if($new_password !== $new_password2){
                $this->error('两次密码不一致');
            }
        }


        //验证Token
        if (!Validate::make()->check(['newpassword' => $new_password], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }

        //模拟一次登录
        $this->auth->direct($this->auth->id);
        $ret = $this->auth->changepwd($new_password, $old_password, !$pwd);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $nickname = $this->request->post('nickname');
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $password2 = $this->request->post('password2');
        $code = $this->request->post('code');
        $captchaId = $this->request->post('captchaId');
        if (!$nickname || !$username || !$password) {
            $this->error('参数不能为空');
        }
        if($password !== $password2){
            $this->error("两次密码不一致");
        }
        // 判断手机号码
        $mobile = "";
        if(preg_match('/^1\d{10}$/', $username) === 1){
            $mobile = $username;
        }
        // 判断邮箱
        $email = "";
        if((new \think\Validate)->rule($username,"email")){
            $email = $username;
        }
        // 验证码
        $auth = Db::name("classroom_code")->where("id",$captchaId)->where("code",$code)->find();
        if(!$auth){
            $this->error('验证码错误，或已失效');
        }
        $ret = $this->auth->register($username, $password, '', '', ["nickname"=>$nickname,"mobile"=>$mobile,"email"=>$email]);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            Db::name("classroom_code")->where("id",$captchaId)->delete();
            $this->success('注册成功', $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 保存头像
     */
    public function avatar()
    {
        $user = $this->auth->getUser();
        $avatar = $this->request->post('avatar');
        if (!$avatar) {
            $this->error("头像不能为空");
        }
        $avatar = str_replace(cdnurl('', true), '', $avatar);
        $user->avatar = $avatar;
        $user->save();
        $this->success('', ['userInfo' => $this->getUserInfo()]);
    }

    /**
     * 保存昵称
     */
    public function save_nickname()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname');
        if (!$nickname) {
            $this->error("昵称不能为空");
        }
        try {
            $user->nickname = $nickname;
            $user->save();
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('修改成功', ['userInfo' => $this->getUserInfo()]);
    }

    /**
     * 获取用户信息
     * @return array
     */
    protected function getUserInfo()
    {
        $userinfo = $this->auth->getUserInfo();
        $userinfo['avatar'] = cdnurl($userinfo['avatar'], true);
        $userinfo['mobile'] = $this->auth->mobile;
        return $userinfo;
    }

    /**
     * 获取用户信息
     */
    public function get_user_info()
    {
        $data = $this->getUserInfo();
        $this->success('ok',$data);
    }


    /**
     * 企业微信登陆
     */
    public function qy_wechat_login()
    {
        $code = input("code");
        if(!$code){
            $this->error("扫码登陆错误，请重试");
        }
        $wechat_model = new Qwechat();

        $data = $wechat_model->wechat_login($code);
        if($data['code'] != 1){
            $this->error($data['msg']);
        }
        $qy_user_id = $data['UserId'];

        // 通过用户ID，获取详细信息
        $userData = $wechat_model->getUser($qy_user_id);

        $user = Db::name("user")->where("username",$qy_user_id)->find();
        if($user){
            $user_id = $user['id'];
            if($user['status'] != 'normal'){
                $this->error('账户已冻结，请联系管理员');
            }
        } else {
            $time = time();
            Db::startTrans();
            try {
                $nickname = isset($userData['data']['name']) ? $userData['data']['name'] : $qy_user_id;
                $user_id = Db::name("user")->insertGetId([
                    'username' => $qy_user_id,
                    'nickname' => $nickname,
                    'bio' => isset($userData['data']['position']) ? $userData['data']['position'] : '',
                    'status' => 'normal',
                    'createtime' => $time,'updatetime' => $time,'jointime' => $time
                ]);
                // WXWork\
                $info = get_addon_info('third');
                if($info && $user_id){
                    Db::name("third")->insert([
                        "user_id" => $user_id,
                        "platform" => "WXWork",
                        "openid" => $qy_user_id,
                        "openname" => $nickname,
                        "createtime" => $time,
                        "updatetime" => $time,
                        "logintime" => $time,
                    ]);
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

        }
        $result = $this->auth->direct($user_id);
        if ($result) {
            $this->success('ok',$this->auth->getUserinfo());
        }
        $this->error();
    }


    /**
     * 微信小程序登录
     */
    public function mp_mini_login()
    {
        $config = get_addon_config('classroom');
        if(empty($config['mp_appID']) || empty($config['mp_appSecret'])){
            $this->error("未配置小程序登陆信息");
        }
        $code = $this->request->post("code");
        $params = [
            'appid'      => $config['mp_appID'],
            'secret'     => $config['mp_appSecret'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            if (isset($json['openid'])) {
                $time = time();
                Db::startTrans();
                try {

                    $user = Db::name("user")->where("username",$json['openid'])->find();
                    if($user){
                        $user_id = $user['id'];
                        if($user['status'] != 'normal'){
                            $this->error('账户已冻结，请联系管理员');
                        }
                    } else {
                        $user_id = Db::name("user")->insertGetId([
                            'username' => $json['openid'],
                            'nickname' => '微信用户',
                            'bio' => '/assets/img/avatar.png',
                            'status' => 'normal',
                            'createtime' => $time,'updatetime' => $time,'jointime' => $time
                        ]);
                        // MiniApp
                        $info = get_addon_info('third');
                        if($info && $user_id){
                            Db::name("third")->insert([
                                "user_id" => $user_id,
                                "platform" => "wechat",
                                "apptype" => "miniapp",
                                "openid" => $json['openid'],
                                "openname" => '微信用户',
                                "createtime" => $time,
                                "updatetime" => $time,
                                "logintime" => $time,
                            ]);
                        }
                    }

                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                $result = $this->auth->direct($user_id);
                if ($result) {
                    $userInfo = $this->auth->getUserinfo();
                    $userInfo['avatar'] = cdnurl($userInfo['avatar'],true);
                    $this->success('ok',$userInfo);
                }
                $this->error("登录失败");
            } else {
                $this->error("登录失败");
            }
        }
        $this->error("登录失败");

    }


}













